package com.weshare.nd.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 序列化反序列号工具
 * @author admin
 *
 */
public class SerializableUtil {

	/**
	 * 序列化
	 * @param obj
	 * @return
	 */
	public static byte[] toBytes(Object obj) {
		byte[] objByte = null;
		
		ByteArrayOutputStream byteOut = null;
		ObjectOutputStream objOut = null;
		
		try {
			byteOut = new ByteArrayOutputStream();
			objOut = new ObjectOutputStream(byteOut);
			
			objOut.writeObject(obj);
			
			objByte = byteOut.toByteArray();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			if(objOut != null){
				try {
					objOut.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(byteOut != null){
				try {
					byteOut.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return objByte;
	}

	/**
	 * 反序列化
	 * @param objByte
	 * @return
	 */
	public static Object toObject(byte[] objByte) {
		ByteArrayInputStream byteInput = new ByteArrayInputStream(objByte);
		
		ObjectInputStream objInput = null;
		Object resultObj = null;
		try {
			objInput = new ObjectInputStream(byteInput);
			resultObj = objInput.readObject();
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			if(objInput != null){
				try {
					objInput.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(byteInput != null){
				try {
					byteInput.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return resultObj;
	}
	
}
